﻿using System;
using System.Web;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.AspNet.Membership.OpenAuth;
using System.Net.Http;
using System.Net.Http.Headers;
using AjaxChatWebApp.DTO;

namespace AjaxChatWebApp.Account
{
    public partial class RegisterExternalLogin : System.Web.UI.Page
    {
        protected string ProviderName
        {
            get { return (string)ViewState["ProviderName"] ?? String.Empty; }
            private set { ViewState["ProviderName"] = value; }
        }

        protected string ProviderDisplayName
        {
            get { return (string)ViewState["ProviderDisplayName"] ?? String.Empty; }
            private set { ViewState["ProviderDisplayName"] = value; }
        }

        protected string ProviderUserId
        {
            get { return (string)ViewState["ProviderUserId"] ?? String.Empty; }
            private set { ViewState["ProviderUserId"] = value; }
        }

        protected string ProviderUserName
        {
            get { return (string)ViewState["ProviderUserName"] ?? String.Empty; }
            private set { ViewState["ProviderUserName"] = value; }
        }

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                ProcessProviderResult();
            }
        }

        protected void logIn_Click(object sender, EventArgs e)
        {
            CreateAndLoginUser();
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            RedirectToReturnUrl();
        }

        private void ProcessProviderResult()
        {
            httpClient.BaseAddress = new Uri("http://localhost:62865");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Process the result from an auth provider in the request
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Account/RegisterExternalLogin.aspx";
            var returnUrl = Request.QueryString["ReturnUrl"];
            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);
            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("External login {0} failed,", ProviderDisplayName);

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Store the provider details in ViewState
            ProviderName = authResult.Provider;
            ProviderUserId = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;


            if(ProviderName == "google")
            {
                ProviderUserId = ProviderUserId.Substring(ProviderUserId.LastIndexOf('=') + 1);
            }





            //get user by email
            User user = null;
            string url = "api/users?provider="+ProviderName+"&providerUserId=" + ProviderUserId;
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                user = response.Content.ReadAsAsync<User>().Result;
            }

            if (user != null)
            {
                // neu ton tai user thi cho dang nhap
                user.Status = true;
                Session["IsLogin"] = true;
                Session["UserId"] = user.Id;
                Session["UserName"] = user.UserName;
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                // neu khong ton tai user thi tao user moi 

                //// Strip the query string from action
                Form.Action = ResolveUrl(redirectUrl);
                userName.Text = authResult.UserName;
            }

        }
        HttpClient httpClient = new HttpClient();
        private void CreateAndLoginUser()
        {
            httpClient.BaseAddress = new Uri("http://localhost:62865");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            if (!IsValid)
            {
                return;
            }



            User us = GetUserInfo();
            HttpResponseMessage response = httpClient.PostAsJsonAsync("api/users", us).Result;
            if (response.IsSuccessStatusCode)
            {
                // them user thanh cong
                // dang nhap
                User user = null;
                //string url = "api/users?provider=" + ProviderName + "&email=" + ProviderUserName;
                //HttpResponseMessage res = httpClient.GetAsync(url).Result;
                //if (response.IsSuccessStatusCode)
                //{
                user = response.Content.ReadAsAsync<User>().Result;
                    Session["IsLogin"] = true;
                    Session["UserId"] = user.Id;
                    Session["UserName"] = user.UserName;
                    Response.Redirect("~/Default.aspx");
                //}


            }
            else
            {
                // thong bao that bai
                //ErrorMessage.Text = "This username has been used. Please choose another username";
            }



        }

        private User GetUserInfo()
        {
            string fileName = "defaultAvatar.png";
            var user = new User
            {
                UserName = userName.Text,
                FirstName = "",
                LastName = "",
                Password = "",
                ProviderUserId = ProviderUserId,
                ProviderUserName = ProviderUserName,
                Status = true,
                Avatar = fileName,
                Provider= ProviderName,
            };

            return user;
        }
        private void RedirectToReturnUrl()
        {
            var returnUrl = Request.QueryString["ReturnUrl"];
            if (!String.IsNullOrEmpty(returnUrl) && OpenAuth.IsLocalUrl(returnUrl))
            {
                Response.Redirect(returnUrl);
            }
            else
            {
                Response.Redirect("~/");
            }
        }
    }
}